package cn.edu.nsmc.modules.sys.service.impl;

import cn.edu.nsmc.common.utils.R;
import cn.edu.nsmc.config.Constant;
import cn.edu.nsmc.modules.sys.dao.SysWorksheetTemplateDao;
import cn.edu.nsmc.modules.sys.dao.SysWorksheetTypeDao;
import cn.edu.nsmc.modules.sys.entity.SysWorksheetTemplate;
import cn.edu.nsmc.modules.sys.entity.data.SysWorksheetTemplateR;
import cn.edu.nsmc.modules.sys.form.WorksheetTemplateList;
import cn.edu.nsmc.modules.sys.service.SysWorksheetTemplateService;
import cn.edu.nsmc.utils.FileConvertUtil;
import cn.edu.nsmc.utils.SmartStringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;

@Service
public class SysWorksheetTemplateServiceImpl extends ServiceImpl<SysWorksheetTemplateDao, SysWorksheetTemplate> implements SysWorksheetTemplateService {
    @Autowired
    private SysWorksheetTemplateDao sysWorksheetTemplateDao;
    @Autowired
    private SysWorksheetTypeDao sysWorksheetTypeDao;
    @Override
    public R getWorksheetTemplateList(WorksheetTemplateList worksheetTemplateList) {
        worksheetTemplateList.setPage((worksheetTemplateList.getPage() - 1) * worksheetTemplateList.getSize());
        List<SysWorksheetTemplateR> list = sysWorksheetTemplateDao.getWorksheetTemplateList(worksheetTemplateList);
        Integer total = sysWorksheetTemplateDao.getWorksheetTemplateListNumber(worksheetTemplateList);
        R r =  R.page("查询成功", list, total);
        return r;
    }

    @Override
    public R addWorksheetTemplate(SysWorksheetTemplate sysWorksheetTemplate) {
        int i = sysWorksheetTemplateDao.insert(sysWorksheetTemplate);
        sysWorksheetTypeDao.addOrUpdateTemplate(sysWorksheetTemplate.getType(),sysWorksheetTemplate.getId());
        return i == 1 ? R.ok("添加成功") : R.error("添加失败");
    }

    @Override
    public R updatedWorksheetTemplate(SysWorksheetTemplate sysWorksheetTemplate) {
        int i = sysWorksheetTemplateDao.updatedWorksheetTemplate(sysWorksheetTemplate);
        sysWorksheetTypeDao.addOrUpdateTemplate(sysWorksheetTemplate.getType(),sysWorksheetTemplate.getId());
        return i == 1 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R deleteWorksheetTemplateByIds(String [] ids) {
        // TODO: 2024/6/28 删除文件
        for (String _id : ids) {
            Long aId = Long.valueOf(_id);
            SysWorksheetTemplate sysWorksheetTemplate = sysWorksheetTemplateDao.selectById(aId);
            sysWorksheetTypeDao.deleteTemplate(sysWorksheetTemplate.getType());
            Integer i = sysWorksheetTemplateDao.deleteById(aId);
            if (i == 0) {
                return R.error("删除失败");
            }
        }
        return R.ok("删除成功");
    }

    @Override
    public List<SysWorksheetTemplate> getList() {
        return list(new LambdaQueryWrapper<SysWorksheetTemplate>().eq(SysWorksheetTemplate::getStatus,1));
    }

    @Override
    public SysWorksheetTemplate getById(Integer templateId) {
        if(templateId == null)return null;
        return getOne(new LambdaQueryWrapper<SysWorksheetTemplate>().eq(SysWorksheetTemplate::getId,templateId).eq(SysWorksheetTemplate::getStatus,1));
    }

    @Override
    /**  * @Description:系统文件在线预览接口  * @Author: tarzan  */
    public R onlinePreview(String path, HttpServletResponse response) throws Exception {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return R.ok();

    }

    @Override
    public void download(String filename, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        File file = new File(Constant.WorksheetTemplateFilepath + filename);
        response.addHeader("Content-Length", String.valueOf(file.length()));
        //表示以二进制流的形式返回
        response.setContentType("application/octet-stream");
        //设置Content-Disposition为inline
        response.addHeader("Content-Disposition", "attachment;filename="
                + URLEncoder.encode(filename, "utf-8").replaceAll("\\+", "%20"));
        //下面这行代码是解决浏览器预览文件时中文乱码的
        response.setContentType(filename.substring(filename.lastIndexOf(".")).toLowerCase() + ";charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }

    @Override
    public R selectById(Long id) {
        SysWorksheetTemplate sysWorksheetTemplate = sysWorksheetTemplateDao.selectById(id);
        return R.success("ok",sysWorksheetTemplate);
    }
}
